//
//  HotpotViewController.m
//  Blank
//
//  Created by whg－54 on 15/9/23.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "HotpotViewController.h"
#import "AppDelegate.h"
//资讯和轮播的model
#import "HotModel.h"
//放置两个button的视图
#import "HomepageTwoView.h"
//资讯页的详情
#import "HomedetailsViewController.h"
#import "HomepageCell.h"
//热点页的详情
#import "IssueViewController.h"
#import "IssueModel.h"
#import "IssueCell.h"
//第三方
#import "NetworkHandle.h"
#import <MJRefresh.h>
#import <UIImageView+WebCache.h>
#import "InfoViewController.h"
//轮播
#import "ADView.h"

#define windth [UIScreen mainScreen].bounds.size.width / 375
#define height ([UIScreen mainScreen].bounds.size.height > 568 ? [UIScreen mainScreen].bounds.size.height : 568) / 667

@interface HotpotViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic , strong) UITableView *tableView;//资讯
@property (nonatomic , strong) UITableView *tableViewIssue;//热点
@property (nonatomic , strong) NSMutableArray *infoArr;
@property (nonatomic , strong) NSMutableArray *keyarr;
@property (nonatomic , strong) NSMutableArray *keyarr1;
@property (nonatomic , strong) NSMutableArray *keyarr2;
@property (nonatomic , strong) NSMutableArray *IssueArr;
@property (nonatomic ,strong) ADView *haveView;
@property (nonatomic , strong) HomepageTwoView *homepageTwoView;

@end

@implementation HotpotViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    self.keyarr = [NSMutableArray array];
//    self.keyarr1 = [NSMutableArray array];
    self.keyarr2 = [NSMutableArray array];
    return self;
}

#pragma mark - 视图加载
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //标题,不透明,背景白色
    self.title = @"腕表";
    self.navigationController.navigationBar.translucent = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self Homepage];
    [self tableViewSubview];
    [self tableViewIssueSubView];
    [self headerFooterHandle];
    [self.tableViewIssue.header beginRefreshing];
    [self.tableView.header beginRefreshing];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeNightModel) name:@"nightModelChange" object:nil];
    
}
- (void) changeNightModel
{
    if ([NightModel getColorModel]) {
        self.tableView.sectionIndexBackgroundColor = [UIColor colorWithRed:57.0f/255 green:79.0f/255 blue:86.0f/255 alpha:1];
        [self.tableViewIssue reloadData];
        [self.tableView reloadData];
    }
    else{
        self.tableView.sectionIndexBackgroundColor = nil;
        [self.tableViewIssue reloadData];
        [self.tableView reloadData];
    }
}

#pragma mark -  刷新、 加载
- (void)headerFooterHandle{
    /* 轮播图解析 */
    NSURLRequest *request1 = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.xbiao.com/app/articleimage"]];
    
    [NSURLConnection sendAsynchronousRequest:request1 queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        /* 缓存 */
        /* 文件夹路径 */
        NSString *path1 = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"slide"];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        /* 创建文件夹 */
        [fileManager createDirectoryAtPath:path1 withIntermediateDirectories:YES attributes:nil error:nil];
        NSString *path = [path1 stringByAppendingPathComponent:@"slide.da"];
        
        if (data != nil)
        {
            id result1 = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSArray *array = result1;
            [array writeToFile:path atomically:YES];
            for (NSDictionary *dicss in result1) {
                HotModel *model2 = [HotModel modelWithDic:dicss];
                [self.keyarr addObject:model2];
                
                [self.keyarr2 addObject:model2.title];
            }
            [self.tableView reloadData];
        }
        else
        {
            NSArray *array = [NSArray arrayWithContentsOfFile:path];
            if (array.count != 0) {
                for (NSDictionary *dicss in array) {
                    HotModel *model2 = [HotModel modelWithDic:dicss];
                    [self.keyarr addObject:model2];
                    [self.keyarr2 addObject:model2.title];

                }
                [self.tableView reloadData];
            }
        }
    }];
    
    /* 资讯刷新 */
    __block NSInteger i = 1;
    self.tableView.header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.xbiao.com/app/articlelist?&pages=0&type=1&time=1439802437825"]];
        [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            if (data != nil) {
                NSMutableArray *refreshArr = [NSMutableArray array];
                i = 2;
                id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                for (NSDictionary *dics in result) {
                    HotModel *model1 = [HotModel modelWithDic:dics];
                    [refreshArr addObject:model1];
                }
                self.infoArr = [NSMutableArray array];
                self.infoArr = refreshArr;
                [self.tableView reloadData];
                [self.tableView.header endRefreshing];
            }else{
                [self.tableView.header endRefreshing];
            }
        }];
    }];
    
    /* 资讯加载 */
    self.tableView.footer = [MJRefreshAutoGifFooter footerWithRefreshingBlock:^{
        NSString *str = @"http://www.xbiao.com/app/articlelist?&type=1&time=1439802437825&pages=";
        NSString *url = [NSString stringWithFormat:@"%@%ld", str, i];
        i++;
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
        [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            if (data != nil) {
            id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                for (NSDictionary *dics in result) {
                    HotModel *model1 = [HotModel modelWithDic:dics];
                    [self.infoArr addObject:model1];
                    if (self.infoArr.count > 0) {
                        [self.tableView reloadData];
                        [self.tableView.footer endRefreshing];
                    }
                }
            }
        }];
    }];
    
    /* 热点刷新 */
    self.tableViewIssue.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        NSMutableArray *arr = [NSMutableArray array];
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.xbiao.com/app/articlelist?&page=0&type=2"]];
        [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            if (data != nil) {
                id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                for (NSDictionary *dics in result) {
                    IssueModel *model1 = [IssueModel IssueModelWithDic:dics];
                    [arr addObject:model1];
                }
                self.IssueArr = [NSMutableArray array];
                self.IssueArr = arr;
                [self.tableViewIssue reloadData];
                [self.tableViewIssue.header endRefreshing];
            }else{
                [self.tableView.header endRefreshing];
            }
        }];
    }];
    
    /* 热点加载 */
    __block NSInteger j = 1;
    self.tableViewIssue.footer = [MJRefreshAutoGifFooter footerWithRefreshingBlock:^{
        NSString *str = @"http://www.xbiao.com/app/articlelist?&type=2&page=";
        NSString *url = [NSString stringWithFormat:@"%@%ld", str, j];
        j++;
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
        [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            if (data != nil) {
                id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                for (NSDictionary *dics in result) {
                    IssueModel *model1 = [IssueModel IssueModelWithDic:dics];
                    [self.IssueArr addObject:model1];
                }
                [self.tableViewIssue reloadData];
                [self.tableViewIssue.footer endRefreshing];
            }
        }];
    }];
}

#pragma mark - 资讯和热点_Button,及其点击事件
- (void)Homepage
{
    /* 自定义View */
    self.homepageTwoView = [[HomepageTwoView alloc] initWithFrame:CGRectMake(windth * 0, 0, windth * 375, height * 40)];
    [self.view addSubview:self.homepageTwoView];
    
    /* Button添加点击事件，实现调转到第二个界面 */
    [self.homepageTwoView.buttonInfo addTarget:self action:@selector(infoBotton:) forControlEvents:UIControlEventTouchUpInside];
    [self.homepageTwoView.buttonNew addTarget:self action:@selector(newButton:) forControlEvents:UIControlEventTouchUpInside];
    if (self.count == 0)
    {
        [self.homepageTwoView.buttonInfo setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        [self.homepageTwoView.buttonNew setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    }
    else{
        [self.homepageTwoView.buttonInfo setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [self.homepageTwoView.buttonNew setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    }
}

- (void)infoBotton:(UIButton *)button
{
    [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [self.homepageTwoView.buttonNew setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    
    self.tableView.frame = CGRectMake(0, height * 40, windth * 375, height * 667);
    self.tableViewIssue.frame = CGRectMake(windth * 375, height * 40, windth * 375, height * 667 - 100);
    [self.tableView reloadData];
}

- (void)newButton:(UIButton *)button
{
    [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [self.homepageTwoView.buttonInfo setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    self.tableViewIssue.frame = CGRectMake(0, height * 40, windth * 375, height * 667 - 100);
    self.tableView.frame = CGRectMake(windth * 375, height * 40, windth * 375, height * 667);
    [self.tableViewIssue reloadData];
}

#pragma mark - 轮播图所在头视图区高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (tableView.tag == 100) {
        return height * 200;
    }
    return height * 0;
}

#pragma mark - TableView上面的滚动视图, 设置分区的头部视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (tableView.tag == 100) {
        if (self.keyarr.count != 0) {
            
            NSMutableArray *arrM = [NSMutableArray array];
            self.keyarr1 = [NSMutableArray array];
            
            for (HotModel *hotModel in _keyarr) {
                [arrM addObject:hotModel.img];
                [self.keyarr1 addObject:hotModel.url];
            }
            NSLog(@"--图片------------=== %@",arrM);
            NSLog(@"-路径---    ------     %@",self.keyarr1);
            
            NSMutableArray *arrtit = [NSMutableArray array];
            for (NSString *ss in self.keyarr2) {
                [arrtit addObject:ss];
            }
            self.haveView = [[ADView alloc] initWithFrame:CGRectMake(windth * 0, 0, windth * 375, 50) dataArr:arrM titleArr:arrtit];
            UITapGestureRecognizer *aTapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGRAction:)];
            aTapGR.numberOfTapsRequired = 1;
            [self.haveView addGestureRecognizer:aTapGR];
            return self.haveView;
        }
    }
    return nil;
}

#pragma mark - 轮播图的点击事件
- (void)tapGRAction:(UIGestureRecognizer *)regi
{
    NSInteger i = self.haveView.scrollView.contentOffset.x / 375 - 1;
    NSString *ss = [self.keyarr1 objectAtIndex:i];
    InfoViewController *nfo = [[InfoViewController alloc] init];
    nfo.urlStr = ss;
    [self.navigationController pushViewController:nfo animated:YES];
    
}

#pragma mark - 资讯的Tableview
- (void)tableViewSubview
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(windth * 0, 40, self.view.frame.size.width, height * (667 - 64)) style:UITableViewStyleGrouped];
    self.tableView.tag = 100;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    [self.tableView registerClass:[HomepageCell class] forCellReuseIdentifier:@"reuse"];
    
}

#pragma mark - 热点的Tableview
- (void)tableViewIssueSubView
{
    self.tableViewIssue = [[UITableView alloc] initWithFrame:CGRectMake(windth * 375, 0, windth * 375, height * 667) style:UITableViewStylePlain];
    self.tableViewIssue.tag = 101;
    self.tableViewIssue.delegate = self;
    self.tableViewIssue.dataSource = self;
    [self.view addSubview:self.tableViewIssue];
    [self.tableViewIssue registerClass:[IssueCell class] forCellReuseIdentifier:@"reuse1"];
}

#pragma mark - 返回分区中的行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView.tag == 100) {
        /* key值的的数量即为分区数 */
        return self.infoArr.count;
    }
    else
        return self.IssueArr.count;
}

#pragma mark - 返回每一行的 cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView.tag == 100) {
        HomepageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        HotModel *model = [self.infoArr objectAtIndex:indexPath.row];
        [cell.leftView sd_setImageWithURL:[NSURL URLWithString:model.img] placeholderImage:[UIImage imageNamed:@"zhanwei"]];
        cell.timeLabel.text = [model.updatetime substringToIndex:10];
        cell.themeLabel.text = model.title;
        cell.siteLable.text = model.brand_name;
        return cell;
    }
    else{
        IssueCell *cell1 = [tableView dequeueReusableCellWithIdentifier:@"reuse1"];
        cell1.selectionStyle = UITableViewCellAccessoryNone;
        IssueModel *model = [self.IssueArr objectAtIndex:indexPath.row];
        [cell1.image sd_setImageWithURL:[NSURL URLWithString:model.img] placeholderImage:[UIImage imageNamed:@"zhanwei"]];
        cell1.TimeLable.text = [model.inputtime substringToIndex:10];
        cell1.ThemeLable.text = model.title;
        cell1.NameLable.text = model.brand_name;
        return cell1;
    }
}

#pragma mark - tableview每一行的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (tableView.tag == 100) {
        return height * 100;
    }else
        return height * 100;
}

#pragma mark - 选中cell时的点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == 100) {
        /* push 新界面, 并且传值 */
        HomedetailsViewController *details = [[HomedetailsViewController alloc] init];
        HotModel *model = self.infoArr[indexPath.row];
        details.url = model.url;
        /* 推出新界面, 使用PushViewController:方法 */
        [self.navigationController pushViewController:details animated:YES];
        
    }
    else{
        IssueViewController *issue = [[IssueViewController alloc] init];
        IssueModel *modell = self.IssueArr[indexPath.row];
        issue.url = modell.url;
        issue.webTitle = modell.title;
        [self.navigationController pushViewController:issue animated:YES];
    }
}


#pragma mark - Memory
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
